package com.oa.srms.apps.dao.student.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oa.srms.apps.dao.student.IMailInfoDao;
import com.oa.srms.apps.entity.student.MailInfoValue;

public class MailInfoDaoImpl extends HibernateDaoSupport implements IMailInfoDao {
	
	@Autowired
	List<MailInfoValue> list;

	@Override
	public Integer addMailInfo(MailInfoValue mailInfoValue) throws Exception {
		if(mailInfoValue != null){
			this.getHibernateTemplate().save(mailInfoValue);
		}
		return mailInfoValue.getMailId();
	}

	@Override
	public void editMailInfo(MailInfoValue mailInfoValue) throws Exception {
		if(mailInfoValue != null){
			this.getHibernateTemplate().update(mailInfoValue);
		}
	}

	@Override
	public MailInfoValue queryByMailId(Integer mailId) throws Exception {
		return (MailInfoValue) this.getHibernateTemplate().get(MailInfoValue.class, mailId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public MailInfoValue queryByMailAndVerifyCode(final String mail, final String verifyCode)
			throws Exception {
		String hqlStr = "FROM MailInfoValue miv WHERE 1=1";
		if (mail != null) {
			hqlStr += " AND miv.mail = ?";
		}
		if (verifyCode != null) {
			hqlStr += " AND miv.verifyCode = ?";
		}
		hqlStr += " AND miv.states = 0";
		final String hql = hqlStr;
		list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				int index = -1;
				if (mail != null) {
					query.setString(++index, mail);
				}
				if (verifyCode != null) {
					query.setString(++index, verifyCode);
				}
				list = query.list();
				return list;
			}
		});
		if( list.size() != 0 && list != null)
			return list.get(0);
		
		return null;
	}

}
